package client

import (
	"fmt"
	"net"
	"strconv"

	"gitee.com/ksbb/go-server/util"
)

type tcpClient struct {
	Ip    string
	Port  int
	Conns net.Conn
}

func newTcpClient(ip string, port int) *tcpClient {
	return &tcpClient{
		Ip:   ip,
		Port: port,
	}
}

//连接
func (t *tcpClient) Conn() {
	listen := t.Ip + ":" + strconv.Itoa(t.Port)
	conn, _ := net.Dial("tcp", listen)
	t.Conns = conn
	Do("Connect")
	Do("Send")
	Do("Recv")
	defer t.Close()
}

func (t *tcpClient) Close() {
	t.Conns.Close()
	do("Close")
}

func do(e string) bool {
	opt, ok := util.OptsT[e] //看有没有注册发送方法
	if ok {
		opt()
		return true
	}
	return false
}

func (t *tcpClient) Send(c net.Conn, s string) {
	c.Write([]byte(s))
}

func (t *tcpClient) Recv(c net.Conn) {
	var buf [1024]byte
	n, _ := c.Read(buf[:])
	fmt.Println(string(buf[:n]))
}
